//
//  DeviceListTableViewController.swift
//  SmartPenSwift
//
//  Created by tql on 2021/2/20.
//

import UIKit
import SmartPenSDK
import SVProgressHUD
import SnapKit

class DeviceListTableViewController: UIViewController {

    var connectBlock : ((_ penName : String) -> Void)?
    
    lazy var devicesListDataSource : NSMutableArray = NSMutableArray.init()
    lazy var tableView : UITableView = {
        var tableView = UITableView.init(frame: self.view.frame, style: .grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(DeviceListEmptyTableCell.classForCoder(), forCellReuseIdentifier: "DeviceListEmptyTableCell")
        return tableView
    }()
    
    let penCommAgent : PenCommAgent = PenCommAgent.getInstance()
    var periphoeral : CBPeripheral?
    var selectedIndex : Int = -1
    
    var bleState : Int32 = 0
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        debugPrint("viewdidload")
        self.view.backgroundColor = .gray
        self.penCommAgent.onBlEScanListener = self
        self.penCommAgent.pensignal = self
        self.penCommAgent .findAllDevices()
        self.navigationItem.title = ""
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "icon-返回"), style: .plain, target: self, action: #selector(back(_ :)))

        self.tableView.frame = CGRect.init(x: 10, y: 10, width: kScreenWidth - 20, height: self.view.frame.size.height - 20 - kBottomSafeHeight)
        self.tableView.backgroundColor = .white
        tableView.layer.cornerRadius = 5
        tableView.layer.shadowColor = UIColor.black.cgColor
        tableView.layer.shadowOffset = CGSize.init(width: 5, height: 5 )
        tableView.layer.shadowOpacity = 0.5
        self.view.addSubview(self.tableView)
        DispatchQueue.global().asyncAfter(deadline: .now()+10) {
            self.stopSearch()
        }
        
//        let swip : UISwipeGestureRecognizer = UISwipeGestureRecognizer.init(target: self, action: #selector(swip(_ :)))
//        swip.delegate = self
//        swip.direction = .right
//        self.view.addGestureRecognizer(swip)
        
        
        let pan : UIPanGestureRecognizer = UIPanGestureRecognizer.init(target: self, action: #selector(pan(_ :)))
        pan.delegate = self
        self.view.addGestureRecognizer(pan)
        self.navigationController?.interactivePopGestureRecognizer?.delegate = self;
        
        
    }
    @objc func swip(_ swip :UISwipeGestureRecognizer){
        
        debugPrint(#function)
        
        debugPrint("\(swip.direction)")
        
        
        
    }
    @objc func pan(_ pan :UISwipeGestureRecognizer){
        
        debugPrint(#function)
        
        
        
        
        
    }
    
    
    func stopSearch() -> Void {
        self.penCommAgent.stopFindAllDevices()
    }
    @objc func back(_ item : UIBarButtonItem) -> Void {
        self.navigationController?.popViewController(animated: true)
    }
     
    @objc func refreshDeviceList() -> Void{
        penCommAgent.interface .cancelAllPeripheralsConnection()
        
        devicesListDataSource.removeAllObjects()
        tableView.reloadData()
        penCommAgent.findAllDevices()
        DispatchQueue.global().asyncAfter(deadline: .now()+10) {
            self.stopSearch()
        }
    }
    

}
extension DeviceListTableViewController : UIGestureRecognizerDelegate{
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        debugPrint(#function)
        
        /*
           CGPoint velocity = [(UIPanGestureRecognizer *)gestureRecognizer velocityInView:self];
             CGPoint location = [gestureRecognizer locationInView:self];
             
             if (velocity.x > 0.0f&&(int)location.x%(int)[UIScreen mainScreen].bounds.size.width<60) {
                 return NO;
             }
             return YES;
         ————————————————
         版权声明：本文为CSDN博主「kst_123」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
         原文链接：https://blog.csdn.net/kst_123/article/details/77762811
         */
        if gestureRecognizer.isKind(of: UIPanGestureRecognizer.classForCoder()) {
            if let pan = gestureRecognizer as? UIPanGestureRecognizer {
                let velocity : CGPoint =  pan.velocity(in: self.view)
                let location : CGPoint = pan.location(in: self.view)
                
                if velocity.x > 0.0 && Int(location.x)%Int((kScreenWidth)) < 60 {
                    return false
                }
                
            }
        }
        
        
        return true
    }
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        debugPrint(#function)
        
        debugPrint("\(gestureRecognizer)aaa\(otherGestureRecognizer)")
        if gestureRecognizer .isKind(of: UIPanGestureRecognizer.classForCoder()) {
            return true
        }else{
            return false
        }
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        debugPrint(#function)
        
        debugPrint("\(gestureRecognizer)aaa\(otherGestureRecognizer)")
        if gestureRecognizer.isEqual(self.navigationController?.interactivePopGestureRecognizer) {
            return true
        }else{
            return false
        }
    }
    
}

extension DeviceListTableViewController : OnBLEScanListener{
    func onScanResult(_ peripheral: CBPeripheral!, advertisementData: [AnyHashable : Any]!, rssi RSSI: NSNumber!) {
        print("finddevice====   \(advertisementData)")
        
        guard advertisementData.keys.contains("kCBAdvDataManufacturerData") else {
            print("not key for kCBAdvDataManufacturerData!!!!")
            return
        }
        
        let data : Data = advertisementData["kCBAdvDataManufacturerData"] as! Data
        
        if BLEDataTransform.getIsSmartPen(data as Data) {
            self.insertTableView(peripheral, advertisementData, RSSI)
        }
        
    }
    func insertTableView(_ peripheral : CBPeripheral, _ advertisementData : [AnyHashable : Any], _ RSSI : NSNumber ) -> Void {
        
        var peripherals : Array = self.devicesListDataSource.value(forKey: "peripheral") as! Array<CBPeripheral>
        
        if !peripherals.contains(peripheral) && (advertisementData["kCBAdvDataManufacturerData"] != nil)    {
            
            var advDataLocalName : String = ""
            if advertisementData.keys.contains("kCBAdvDataLocalName") {
                advDataLocalName  = advertisementData["kCBAdvDataLocalName"] as! String
            }
            
            
            var indexPaths : NSMutableArray = NSMutableArray.init()
            var indexPath = NSIndexPath.init(row: peripherals.count, section: 0)
            indexPaths.add(indexPath)
            var  item : NSMutableDictionary = NSMutableDictionary.init()
            item.setValue(peripheral, forKey: "peripheral")
            item.setValue(RSSI, forKey: "RSSI")
            
            item.setValue(advertisementData, forKey: "advertisementData")
            self.devicesListDataSource.add(item)
            if self.devicesListDataSource.count == 1 {
                self.tableView.reloadData()
            }else{
                self.tableView.insertRows(at: indexPaths as! [IndexPath], with: .automatic)
            }
        }
    }
}
extension DeviceListTableViewController : TQLPenSignal{
    
    func didUpdatecentralManagerState(_ state: Int32) {
        
        bleState = state
        
        if state != 5 {
            self.refreshDeviceList()
            if state == 4 {
                SVProgressHUD.showError(withStatus: "蓝牙开关没打开");
                self.tableView.reloadData()
            }else{
                SVProgressHUD.showError(withStatus: "蓝牙没授权");
                self.tableView.reloadData()
            }
        }
        
    }
    
    func onDisconnected() {
        SVProgressHUD .showSuccess(withStatus: "断开连接")
        self .refreshDeviceList()
    }
    
    func onConnectFailed() {
        SVProgressHUD.showError(withStatus: "连接失败")
    }
    func onfinishUpdateCharacteric() {
        self.penCommAgent.reqOfflineDataInfo()
        if self.connectBlock != nil {
            let  item : NSDictionary = self.devicesListDataSource[selectedIndex] as! NSDictionary
            let peripheral : CBPeripheral = item["peripheral"] as! CBPeripheral
            self.connectBlock!((peripheral.name ?? periphoeral?.identifier.uuidString) ?? "unknown")
        }
        DispatchQueue.main.async {
            
            SVProgressHUD.setGraceTimeInterval(2)
            SVProgressHUD.showSuccess(withStatus: "笔连接成功")
        }
        
        DispatchQueue.global().asyncAfter(deadline: .now()+2) {
            DispatchQueue.main.async {
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
}

extension DeviceListTableViewController : UITableViewDelegate{
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 100
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if self.devicesListDataSource.count==0 {
            return self.view.frame.size.height - 100
        }else{
            return 77
        }
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headView : UIView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.tableView.frame.size.width, height: 100))
        headView.backgroundColor = .white
        let titleLabel : UILabel = UILabel.init()
        titleLabel.text = "连接智能笔MAC编号"
        titleLabel.font = UIFont.systemFont(ofSize: 25)
        titleLabel.textColor = UIColor.init(hex: "0x151515")
        headView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalTo(headView).offset(16)
            make.top.equalTo(headView).offset(31)
        }
        
        let subTitleLabel : UILabel = UILabel.init()
        subTitleLabel.text = "查看笔尾MAC编号，连接智能笔"
        subTitleLabel.font = UIFont.systemFont(ofSize: 16)
        subTitleLabel.textColor = UIColor.init(hex: "0x505050")
        headView.addSubview(subTitleLabel)
        subTitleLabel.snp.makeConstraints { (make) in
            make.left.equalTo(headView).offset(16)
            make.top.equalTo(titleLabel.snp_bottomMargin).offset(11)
        }
        
        
        
        return headView
    }
}

extension DeviceListTableViewController : UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         
        if self.devicesListDataSource.count == 0 {
            return 1
        }
        return self.devicesListDataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if self.devicesListDataSource.count == 0 {
            let cell : DeviceListEmptyTableCell = tableView.dequeueReusableCell(withIdentifier: "DeviceListEmptyTableCell") as! DeviceListEmptyTableCell
            cell.state = bleState
            return cell
        }
        
        
        var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        if cell==nil {
            cell = UITableViewCell.init(style: .default, reuseIdentifier: "cell")
        }
        
        var item : NSMutableDictionary = self.devicesListDataSource[indexPath.row] as! NSMutableDictionary
        var peripheral : CBPeripheral = item["peripheral"] as! CBPeripheral
        var advertisementData : NSDictionary = item["advertisementData"] as! NSDictionary
        
        var data : Data = advertisementData["kCBAdvDataManufacturerData"] as! Data
        var macAddress : String = BLEDataTransform.getNewMacAdress(data)
        cell?.textLabel?.text = macAddress
        cell?.detailTextLabel?.text = peripheral.name
        
        return cell!
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if self.devicesListDataSource.count==0 {
            self.refreshDeviceList()
            return
        }
        
        self.penCommAgent.interface.cancelAllPeripheralsConnection()
        self.penCommAgent.stopFindAllDevices();
        self.tableView.deselectRow(at: indexPath, animated: false)
        selectedIndex = indexPath.row
        
        let   item : NSDictionary = self.devicesListDataSource[indexPath.row] as! NSDictionary
        let advertisementData : NSDictionary  = item["advertisementData"] as! NSDictionary
        let data : Data = advertisementData["kCBAdvDataManufacturerData"] as! Data
        
        if BLEDataTransform.getIsSmartPen(data) == false {
            SVProgressHUD.showError(withStatus: "请选择支持的智能笔")
            return
        }
        
        let Iperipheral = item["peripheral"] as! CBPeripheral
//        self.periphoeral = periphoeral
        
        DispatchQueue.global().asyncAfter(deadline: .now()+1) {
//            [weak self]
            self.penCommAgent.connect(Iperipheral)
        }
        
        SVProgressHUD.show(withStatus: "配对中")
        
        
        
    }
    
    
    
}

